#include <head.h>

// pthread_mutex_t lock; // 定义互斥锁

typedef struct can
{
    int sum;   // 设定几份线程
    int count; // 第几份线程
} can;

void *copy_file(void *can1)
{
    can *c = (can *)can1;
    char ch;
    int count1 = 0;
    int fd = open("123.txt", O_RDONLY);
    int fd1 = open("123_1.txt", O_RDWR | O_APPEND);

    lseek(fd, 0, SEEK_SET);

    while (read(fd, &ch, 1) != 0)
    {
        count1++;
    }
    lseek(fd, c->count * (count1 / c->sum), SEEK_SET);
    // printf("%d\n",count1);
    // pthread_mutex_lock(&lock);
    for (size_t i = 0; i <= count1 / c->sum; i++)
    {

        read(fd, &ch, 1);

        write(fd1, &ch, 1);
    }
  // pthread_mutex_unlock(&lock);

    close(fd);
    close(fd1);
}

int main(int argc, char const *argv[])
{
    int j;
    printf("请输入你要几个线程用来拷贝文件");
    scanf("%d", &j);
    can can = {.sum = j};
    pthread_t tid[j]; // 定义线程id数组
    for (size_t i = 0; i < j; i++)
    {
        getchar();
        can.count = i;
        if (0 != pthread_create(&tid[i], NULL, copy_file, (void *)&can)) // 创建线程
        {
            exit(-1);
        }
        // pthread_detach(tid[i]); // 线程分离
    }
    for (size_t i = 0; i < j; i++)
    {
        pthread_join(tid[i], NULL); // 线程回收
    }

    return 0;
}

// pthread_mutex_destroy(&lock); // 销毁互斥锁
